/**
 *  Created by IntelliJ IDEA.
 *  User: Bestick
 *  Date: 2016/7/13
 *  Time: 13:16
 *  Url: http://www.bestick.cn
 *  Copyright © 2015-2016 Bestick All rights reserved
 *  -----------------------------------------------------------
 *  会当凌绝顶，一览众山小。
 */

/**
 * 退出登录
 */
function logout() {
    layer.msg("确定要退出吗", {
        shade: 0.3,
        shadeClose: true,
        icon: 3,
        time: 0,
        btn: ['确定', '取消'],
        yes: function () {
            location.assign("api/user/logout.html");
        }
    });
}



$(function () {

    var themeNum=1;

    var homeURL = "/api/user/getcurrentuserinfo.html";
    
    var homeMap = {
        "#home-temp": "#home",
        "#home-wr-temp": "#home-wr",
        "#home-sr-temp": "#home-sr"
    };

    $('#health').mouseenter(function () {
        $(this).next().next().addClass('health-marker');
        $('#home-wr').removeClass('hidden').next().addClass('hidden');
    }).mouseleave(function () {
        var $marker = $('#marker');
        $marker.hasClass('study-marker') ? $marker.removeClass('study-marker').addClass('health-marker') : $marker.addClass('health-marker');
    });

    $('#study').mouseenter(function () {
        $(this).next().addClass('study-marker');
        $('#home-sr').removeClass('hidden').prev().addClass('hidden');
    }).mouseleave(function () {
        var $marker = $('#marker');
        $marker.hasClass('health-marker') ? $marker.removeClass('health-marker').addClass('study-marker') : $marker.addClass('study-marker');
    });

    $('.change-mood').hover(function () {
        $('.music-ico').addClass('hidden');
    },function () {
        $('.music-ico').removeClass('hidden');
    }).click(function () {
        themeNum++;
        if (themeNum > 3) {
            themeNum=1;
            $('#bg-music-src'+Number(3))[0].pause();
            $('#bg-music-src'+Number(1))[0].play();
        }
        $('#wr-banner').css('background',"url(" + "'http://ocuddscaa.bkt.clouddn.com/image/jpg/banner" + themeNum + ".jpg') center/cover no-repeat");
        if (themeNum <4 && themeNum > 1) {
            $('#bg-music-src'+Number(themeNum)).prev()[0].pause();
            $('#bg-music-src'+Number(themeNum))[0].play();
        }
    });

    doRender(
        homeURL,
        null,
        homeMap,
        function (XMLHttpRequest) {
            $('#wr-loading-box').addClass('hidden');
            initHomePage(XMLHttpRequest);
        }
    );

    /**
     * 初始化首页
     */
    function initHomePage(XMLHttpRequest) {


        //体重记录图表
        $('#btn-graph').click(function () {
            $('#box-graph').removeClass('hidden').next().addClass('hidden');
            initHighchart(min, max);
        });

        //体重记录表格
        $('#btn-statistic').click(function () {
            $('#box-statistic').removeClass('hidden').prev().addClass('hidden');
        });

        //学习记录图表
        $('#s-btn-graph').click(function () {
            $('#s-box-graph').removeClass('hidden').next().addClass('hidden');
            // initHighchart(min, max);
        });

        //学习记录表格
        $('#s-btn-statistic').click(function () {
            $('#s-box-statistic').removeClass('hidden').prev().addClass('hidden');
        });

        /**
         * 鼠标hover表格tr颜色
         */
        $('.table-hover tr').hover(function () {
            $(this).css('background', 'rgba(0,0,0,.2)');
        },function () {
            $(this).css('background', 'rgba(0,0,0,0)');
        });

        $('#s-box-statistic .table-hover tr').click(function () {
            layer.open({
                type: 1,
                shade: false,
                skin: 'layer-custom-box',
                title: false, //不显示标题
                content: '1. getup：' + $(this).find('td:eq(1)').html() + '&nbsp;&nbsp;&Iota;&nbsp;&nbsp;go2bed：' + $(this).find('td:eq(2)').html() + '<br />'
                        + '2. content：' + $(this).find('td:eq(3)').html() + '<br />' + '3. time：' + $(this).find('td:eq(4)').html(), //捕获的元素
                cancel: function(index){
                    layer.close(index);
                }
            });
        });

        $('.change-mood').removeClass('hidden');

        $('#clock').countdown('2016/12/24', function(event) {
            $(this).html(event.strftime('%D 天 %H 时 %M 分 %S 秒'));
        });

        $("#getup-time").timeDropper({
            meridians: false,
            format: 'HH:mm',
        });
        $("#go2bed-time").timeDropper({
            meridians: false,
            format: 'HH:mm',
        });

        /**
         * 控制min和max输入框宽度变化
         */
        $('.number').bind('input propertychange', function () {
            var width = $(this).width();
            var value = $(this).val();
            if (value >= 100) {
                $(this).css('width', 88);
            } else {
                $(this).css('width', 64);
            }
        });

        function checkSubmit() {
            var min = Number($('#min').val());
            var max = Number($('#max').val());
            // var today = new Date().get
            if (min == '' || max == '') {
                showErrorInfo("记录值不能为空");
                return false;
            }
            if (min > max) {
                showErrorInfo("您的记录值是不是填反了···");
                return false;
            }
            if (min < 30 || max < 30) {
                showErrorInfo("你丫这么瘦还玩啥塑身，快好吃好喝去···");
                return false;
            }
            if (max > 200 || min > 200) {
                showErrorInfo("天呐，您的体重已经爆表了···");
                return false;
            }
            return true;
        }

        $('#btn-submit').click(function () {
            if (!checkSubmit()) {
                return;
            }
            layer.msg("最大值:" + $("#max").val() + ",最小值:" + $("#min").val(), {
                shade: 0.3,
                shadeClose: true,
                icon: 3,
                time: 0,
                btn: ['确定', '取消'],
                yes: function () {
                    $.ajax({
                        type: 'GET',
                        data: {
                            minWeight: $('#min').val(),
                            maxWeight: $('#max').val(),
                            userId: $('#userId').val()
                        },
                        url: "/api/record/addrecord.html",
                        success: function (result) {
                            if (result.status == 1) {
                                showInfo(result.msg, function () {
                                    $('#wr-loading-box').removeClass('hidden');
                                    doRender(
                                        homeURL,
                                        null,
                                        homeMap,
                                        function (XMLHttpRequest) {
                                            $('#wr-loading-box').addClass('hidden');
                                            initHomePage(XMLHttpRequest);
                                        }
                                    );
                                });
                            } else {
                                if(result.msg == "" || result.msg == null) {
                                    showErrorInfo("空，未知错误信息请联系管理员");
                                    return;
                                }
                                showErrorInfo(result.msg);
                            }
                        },
                        error: function () {
                            showErrorInfo('系统或者网络出错，请联系管理员解决');
                        }
                    });
                }
            });
        });

        $('#s-btn-submit').click(function () {
            if ($('#getup-time').val() == '' || $('#go2bed-time').val() == ''|| $('#today-sum').val() == '') {
                showErrorInfo("记录值不能为空");
                return false;
            }
            layer.msg("确定提交吗", {
                shade: 0.3,
                shadeClose: true,
                icon: 3,
                time: 0,
                btn: ['确定', '取消'],
                yes: function () {
                    $.ajax({
                        type: 'POST',
                        data: {
                            studyGetupTime: $('#getup-time').val().replace(/<\/?[^>]*>/g, ''), //去掉html标记
                            studyGo2bedTime: $('#go2bed-time').val().replace(/<\/?[^>]*>/g, ''),
                            studyTodaySum: $('#today-sum').val().replace(/<\/?[^>]*>/g, ''),
                            userId: $('#userId').val()
                        },
                        url: "/api/record/addstudyrecord.html",
                        success: function (result) {
                            if (result.status == 1) {
                                showInfo(result.msg, function () {
                                    $('#wr-loading-box').removeClass('hidden');
                                    doRender(
                                        homeURL,
                                        null,
                                        homeMap,
                                        function (XMLHttpRequest) {
                                            $('#wr-loading-box').addClass('hidden');
                                            initHomePage(XMLHttpRequest);
                                        }
                                    );
                                });
                            } else {
                                if(result.msg == "" || result.msg == null) {
                                    showErrorInfo("空，未知错误信息请联系管理员");
                                    return;
                                }
                                showErrorInfo(result.msg);
                            }
                        },
                        error: function () {
                            showErrorInfo('系统或者网络出错，请联系管理员解决');
                        }
                    });
                }
            });
        });

        var records = XMLHttpRequest.responseJSON.data.recordList;
        var max = new Array();
        var min = new Array();

        for (var prop in records) {
            // console.log(records[prop])
            max[prop] = [parseInt(records[prop].recordTime), parseFloat(records[prop].maxWeight)];
            min[prop] = [parseInt(records[prop].recordTime), parseFloat(records[prop].minWeight)];
        }

        //数据升序，HighChart需要
        min.reverse()
        max.reverse()

        Highcharts.theme = {
            colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee",
                "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"],
            chart: {
                backgroundColor: {
                    linearGradient: [0, 0, 250, 500],
                    stops: [
                        [0, 'rgba(48, 96, 48, .85)'],
                        [1, 'rgba(0, 0, 0, .85)']
                    ]
                },
                borderColor: '#000000',
                borderWidth: 0,
                className: 'dark-container',
                plotBackgroundColor: 'rgba(255, 255, 255, .1)',
                plotBorderColor: '#CCCCCC',
                plotBorderWidth: 1
            },
            title: {
                style: {
                    color: '#C0C0C0',
                    font: 'bold 16px "Trebuchet MS", Verdana, sans-serif'
                }
            },
            subtitle: {
                style: {
                    color: '#666666',
                    font: 'bold 12px "Trebuchet MS", Verdana, sans-serif'
                }
            },
            xAxis: {
                gridLineColor: '#333333',
                gridLineWidth: 1,
                labels: {
                    style: {
                        color: '#A0A0A0'
                    }
                },
                lineColor: '#A0A0A0',
                tickColor: '#A0A0A0',
                title: {
                    style: {
                        color: '#CCC',
                        fontWeight: 'bold',
                        fontSize: '12px',
                        fontFamily: 'Trebuchet MS, Verdana, sans-serif'

                    }
                }
            },
            yAxis: {
                gridLineColor: '#333333',
                labels: {
                    style: {
                        color: '#A0A0A0'
                    }
                },
                lineColor: '#A0A0A0',
                minorTickInterval: null,
                tickColor: '#A0A0A0',
                tickWidth: 1,
                title: {
                    style: {
                        color: '#CCC',
                        fontWeight: 'bold',
                        fontSize: '12px',
                        fontFamily: 'Trebuchet MS, Verdana, sans-serif'
                    }
                }
            },
            tooltip: {
                backgroundColor: 'rgba(0, 0, 0, 0.75)',
                style: {
                    color: '#F0F0F0'
                }
            },
            toolbar: {
                itemStyle: {
                    color: 'silver'
                }
            },
            plotOptions: {
                line: {
                    dataLabels: {
                        color: '#CCC'
                    },
                    marker: {
                        lineColor: '#333'
                    }
                },
                spline: {
                    marker: {
                        lineColor: '#333'
                    }
                },
                scatter: {
                    marker: {
                        lineColor: '#333'
                    }
                },
                candlestick: {
                    lineColor: 'white'
                }
            },
            legend: {
                itemStyle: {
                    font: '9pt Trebuchet MS, Verdana, sans-serif',
                    color: '#A0A0A0'
                },
                itemHoverStyle: {
                    color: '#FFF'
                },
                itemHiddenStyle: {
                    color: '#444'
                }
            },
            credits: {
                style: {
                    color: '#666'
                }
            },
            labels: {
                style: {
                    color: '#CCC'
                }
            },
            navigation: {
                buttonOptions: {
                    symbolStroke: '#DDDDDD',
                    hoverSymbolStroke: '#FFFFFF',
                    theme: {
                        fill: {
                            linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                            stops: [
                                [0.4, '#606060'],
                                [0.6, '#333333']
                            ]
                        },
                        stroke: '#000000'
                    }
                }
            },

            // scroll charts
            rangeSelector: {
                buttonTheme: {
                    fill: {
                        linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                        stops: [
                            [0.4, '#888'],
                            [0.6, '#555']
                        ]
                    },
                    stroke: '#000000',
                    style: {
                        color: '#CCC',
                        fontWeight: 'bold'
                    },
                    states: {
                        hover: {
                            fill: {
                                linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                                stops: [
                                    [0.4, '#BBB'],
                                    [0.6, '#888']
                                ]
                            },
                            stroke: '#000000',
                            style: {
                                color: 'white'
                            }
                        },
                        select: {
                            fill: {
                                linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                                stops: [
                                    [0.1, '#000'],
                                    [0.3, '#333']
                                ]
                            },
                            stroke: '#000000',
                            style: {
                                color: 'yellow'
                            }
                        }
                    }
                },
                inputStyle: {
                    backgroundColor: '#333',
                    color: 'silver'
                },
                labelStyle: {
                    color: 'silver'
                }
            },

            navigator: {
                handles: {
                    backgroundColor: '#666',
                    borderColor: '#AAA'
                },
                outlineColor: '#CCC',
                maskFill: 'rgba(16, 16, 16, 0.5)',
                series: {
                    color: '#7798BF',
                    lineColor: '#A6C7ED'
                }
            },

            scrollbar: {
                barBackgroundColor: {
                    linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                    stops: [
                        [0.4, '#888'],
                        [0.6, '#555']
                    ]
                },
                barBorderColor: '#CCC',
                buttonArrowColor: '#CCC',
                buttonBackgroundColor: {
                    linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                    stops: [
                        [0.4, '#888'],
                        [0.6, '#555']
                    ]
                },
                buttonBorderColor: '#CCC',
                rifleColor: '#FFF',
                trackBackgroundColor: {
                    linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
                    stops: [
                        [0, '#000'],
                        [1, '#333']
                    ]
                },
                trackBorderColor: '#666'
            },

            // special colors for some of the
            legendBackgroundColor: 'rgba(0, 0, 0, 0.5)',
            background2: 'rgb(35, 35, 70)',
            dataLabelsColor: '#444',
            textColor: '#C0C0C0',
            maskColor: 'rgba(255,255,255,0.3)'
        };

        // Apply the theme
        Highcharts.setOptions(Highcharts.theme);

        Highcharts.setOptions({
            global: {
                useUTC: false //关闭UTC
            }
        });

        function initHighchart(min, max) {
            /**
             * 初始化图表
             */
            $('#box-graph').highcharts({
                chart: {
                    type: 'spline',
                    zoomType: 'xy'
                },
                title: {
                    text: 'WeightRecord'
                },
                credits: {
                    text: 'www.bestick.cn',
                    href: 'http://www.bestick.cn'
                },
                xAxis: {
                    type: 'datetime',
                    labels: {
                        formatter: function () {
                            return new Date(parseInt(this.value)).toLocaleDateString();
                        }
                    },
                    tickInterval: 7 * 24 * 3600 * 1000
                },
                yAxis: {
                    title: {
                        text: '体重 (kg)'
                    }
                },
                tooltip: {
                    crosshairs: true,
                    xDateFormat: '%Y-%m-%d %H:%M:%S',
                    shared: true
                },
                plotOptions: {
                    spline: {
                        dataLabels: {
                            enabled: true
                        },
                        marker: {
                            radius: 4,
                            lineColor: '#666666',
                            lineWidth: 1
                        },
                        animation: true
                    }
                },
                series: [{
                    name: '最大值',
                    data: max
                }, {
                    name: '最小值',
                    data: min
                }]
            });
        }

        initHighchart(min, max);
    }
});